<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <CommunityTree @node-click="handleCommunityNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="" prop="keyWord">
            <el-input placeholder="请输入内容" v-model.trim="keyWord">
              <template #prepend>
                <el-select v-model="kType" placeholder="请选择" class="!w-120px">
                  <el-option label="电表名称" value="meterName" />
                  <el-option label="电表编码" value="meterNo" />
                  <el-option label="集中器/采集器编码" value="meterSerialServerNo" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="" prop="elecOpenFlag">
            <el-select
              v-model="queryParams.elecOpenFlag"
              placeholder="通电状态"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in meterElectOpenStateDictDatas"
                :key="parseInt(dict.value)"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
            <el-select
              v-model="queryParams.protectFlag"
              placeholder="保电状态"
              clearable
              class="!w-120px"
            >
              <el-option
                v-for="dict in protects"
                :key="parseInt(dict.value)"
                :label="dict.label"
                :value="parseInt(dict.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button
              type="primary"
              plain
              @click="openForm('create', undefined, queryParams.commId)"
              v-hasPermi="['zwsj:meter:create']"
            >
              <Icon icon="ep:plus" /> 新增
            </el-button>
            <el-button
              type="warning"
              plain
              @click="handleImport"
              v-hasPermi="['zwsj:meter:import']"
            >
              <Icon icon="ep:upload" /> 导入
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list">
          <el-table-column
            label="社区/电表名称/编码/安装位置"
            align="left"
            prop="meterName"
            min-width="330"
          >
            <template #default="scope">
              <div> 社区：{{ scope.row.community.name }} </div>
              <div>
                名称：<el-link type="primary" @click="showMeter(scope.row.id)">{{
                  scope.row.meterName
                }}</el-link>
              </div>
              <div> 
                编码：<label>{{ scope.row.meterNo }} </label> 
                <span style="color:green;" v-if="scope.row.onlineFlag == 1">在线</span><span style="color:red;" v-if="scope.row.onlineFlag == 0">离线</span>
                <dict-tag v-if="scope.row.serialServer" :type="DICT_TYPE.METER_FACTORY" :value="scope.row.serialServer.factoryCode" />
              </div>
              <div>
                位置：<el-button
                  type="primary"
                  link
                  :icon="Edit"
                  @click="handleInstall(scope.row)"
                  v-hasPermi="['zwsj:meter:update']"
                >
                  {{ scope.row.bindAddresses }}</el-button
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column label="参数" align="left" prop="voltage" width="130">
            <template #default="scope">
              <div> 保电：{{ scope.row.protectFlag == 1 ? '是' : '否' }}</div>
              <div> 功率：{{ scope.row.power }}</div>
              <div> 电流：{{ scope.row.elecCurrent }}</div>
              <div> 总kWh：{{ scope.row.totalKwh }}</div>
            </template>
          </el-table-column>
          <!-- <el-table-column label="其他参数" align="left" width="130">
            <template #default="scope">
              <div> 尖kWh：{{ scope.row.sharpKwh }}</div>
              <div> 峰kWh：{{ scope.row.peakKwh }}</div>
              <div> 平kWh：{{ scope.row.flatKwh }}</div>
              <div> 谷kWh：{{ scope.row.valleyKwh }}</div>
            </template>
          </el-table-column> -->
          <el-table-column label="余额" align="center" prop="lastBalance" width="120" />
          <el-table-column label="状态/最后连接时间" align="left" prop="elecOpenFlag" width="180">
            <template #default="scope">
              <div>通电状态：<dict-tag :type="DICT_TYPE.METER_ELECT_OPEN_STATE" :value="scope.row.elecOpenFlag" /></div>
              <div>使用状态：<dict-tag :type="DICT_TYPE.METER_USE_STATUS" :value="scope.row.useStatus" /></div>
              <div>用电上报：<dict-tag :type="DICT_TYPE.METER_REPORT_FLAG" :value="scope.row.reportFlag" /></div>
              <div>{{ scope.row.lastConnecttime}}</div>
            </template>
          </el-table-column>
          <el-table-column label="银联账户" align="center" fixed="right" width="90">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="showOwnMeterConfig(scope.row.ownMeterConfigRespVO.id)"
                v-if="scope.row.ownMeterConfigRespVO != null"
              >
                <!-- {{ scope.row.ownMeterConfigRespVO.memberUserName }} -->
                  {{scope.row.ownMeterConfigRespVO.configRemark}}
                </el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="120">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['zwsj:meter:update']"
              >
                修改
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['zwsj:meter:delete']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 添加或修改房屋对话框 -->
  <MeterForm ref="formRef" @success="getList" />
  <!-- 导入对话框 -->
  <MeterImportForm ref="importFormRef" @success="getList" />
  <OwnMeterConfigView ref="showOwnMeterConfigRef" />
  <MeterView ref="showMeterRef" />
  <EquipBind ref="equipBindRef" @refresh-list="getList" />
</template>
<script lang="ts" setup>
import { Edit } from '@element-plus/icons-vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as MeterApi from '@/api/zwsj/meter'
import MeterForm from './MeterForm.vue'
import MeterImportForm from './MeterImportForm.vue'
import CommunityTree from '@/views/zwsj/common/CommunityTree.vue'
import OwnMeterConfigView from '@/views/zwsj/ownMeterConfig/OwnMeterConfigView.vue'
import MeterView from '@/views/zwsj/meter/MeterView.vue'
import EquipBind from '@/views/zwsj/equipBind/index.vue'

defineOptions({ name: 'Meter' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const meterElectOpenStateDictDatas = getIntDictOptions(DICT_TYPE.METER_ELECT_OPEN_STATE)
const protects = ref([
  {
    value: 1,
    label: '保电中'
  },
  {
    value: 0,
    label: '不保电'
  }
])

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数

const keyWord = ref('')
const kType = ref('meterName')
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  commId: null,
  meterName: '',
  meterNo: '',
  meterSerialServerNo: '',
  elecOpenFlag: null
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
      queryParams.meterName = ''
      queryParams.meterNo = ''
    if (kType.value == 'meterName') {
      queryParams.meterName = keyWord.value
    } else if (kType.value == 'meterNo') {
      queryParams.meterNo = keyWord.value
    } else if (kType.value == 'meterSerialServerNo'){
      queryParams.meterSerialServerNo = keyWord.value
    }

    const data = await MeterApi.getMeterPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  keyWord.value = undefined
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 处理区域被点击 */
const handleCommunityNodeClick = async (row) => {
  queryParams.commId = row.id
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number, commId?: number) => {
  formRef.value.open(type, id, commId)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MeterApi.deleteMeter(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 显示电表 */
const showMeterRef = ref()
const showMeter = async (meterId: number) => {
  showMeterRef.value.open(meterId)
}

const showOwnMeterConfigRef = ref()
const showOwnMeterConfig = async (ownMeterConfigId: number) => {
  showOwnMeterConfigRef.value.open(ownMeterConfigId)
}

const equipBindRef = ref()
const handleInstall = async (row: any) => {
  let positionType = "room";
  equipBindRef.value.open(row.id, 'meter',positionType, row.commId, row.meterName)
}


/** 导入 */
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>
